//
//  UserFeedBackController.m
//  takeout
//
//  Created by Mac on 12-1-7.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "UserFeedBackController.h"
#import "MoreManager.h"

@implementation UserFeedBackController
@synthesize textViews;
@synthesize contactTextViews;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //添加手势
    //后退
    UISwipeGestureRecognizer *recognizer; 
    recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [[self view] addGestureRecognizer:recognizer];
    
    self.navigationController.navigationBarHidden = NO; 
    
    self.title = [recieveDictionary objectForKey:@"title"];
    //定义导航栏左侧按钮
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0,0,54,27)];
    NSString *filePath=[[NSBundle mainBundle] pathForResource:@"navLeftBtn" ofType:@"png"];
    [leftButton setBackgroundImage:[UIImage imageWithContentsOfFile:filePath] forState:UIControlStateNormal];
    [leftButton setBackgroundImage:[UIImage imageWithContentsOfFile:filePath] forState:UIControlStateHighlighted];
    [leftButton setTitle:@"返 回" forState:UIControlStateNormal];
    leftButton.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:14]; 
    [leftButton addTarget:self action:@selector(backButtonPressd) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    //设置为左边按钮
    [[self navigationItem] setLeftBarButtonItem:leftItem];

    
    //定义导航栏右侧按钮
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0,0,54,27)];
    NSString *filePath2=[[NSBundle mainBundle] pathForResource:@"navRightBtn" ofType:@"png"];
    [rightButton setBackgroundImage:[UIImage imageWithContentsOfFile:filePath2] forState:UIControlStateNormal];
    [rightButton setBackgroundImage:[UIImage imageWithContentsOfFile:filePath2] forState:UIControlStateHighlighted];
    [rightButton setTitle:@"提 交" forState:UIControlStateNormal];
    rightButton.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:14]; 
    [rightButton addTarget:self action:@selector(sendReport:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    //设置为左边按钮
    [[self navigationItem] setRightBarButtonItem:rightItem];

    //添加说明
    NSString *type = [recieveDictionary objectForKey:@"type"];
    NSString *tipMsg;
    NSString *tipText;
    if ([type isEqualToString:@"F"]) {
        tipMsg = [[NSString alloc] initWithFormat:@"欢迎您提出宝贵的意见和建议，您留下的每个字都将用来改善我们的软件。"];
        tipText = [[NSString alloc] initWithFormat:@"请输入您的反馈意见（500字以内）"];
    }else{
        tipMsg = [[NSString alloc] initWithFormat:@"感谢您报告商户的错误信息，我们会将处理结果发送至您的邮箱。"];
        tipText = [[NSString alloc] initWithFormat:@"请输入错误信息（500字以内）"];
    }
    UITextView *explainTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, 0, 300, 50)];
    explainTextView.text=tipMsg;
    explainTextView.font=[UIFont fontWithName:@"Helvetica-Bold" size:14];
    [explainTextView setTextColor:[UIColor colorWithRed:255.0/255.0 green:111.0/255.0 blue:6.0/255.0 alpha:1.0f]];
    explainTextView.editable = NO;
    [self.view addSubview:explainTextView];
    
    
    UIImageView* bgView=[[UIImageView alloc] initWithFrame:CGRectMake(0,60,320,160)];
    NSString *filePath4=[[NSBundle mainBundle] pathForResource:@"text" ofType:@"png"];
    [bgView setImage:[UIImage imageWithContentsOfFile:filePath4]];  
    [bgView setUserInteractionEnabled:YES];  
    
    //添加反馈信息的文本框
    textViews = [[UIPlaceHolderTextView alloc] initWithFrame:CGRectMake(15, 10, 290, 140)];    
    //把换行键改成完成键
    textViews.returnKeyType = UIReturnKeyDone;
    textViews.textColor = [UIColor blackColor];
	textViews.font = [UIFont fontWithName:@"Arial" size:16.0];
    textViews.delegate = self;
	textViews.backgroundColor = [UIColor whiteColor];
//    self.textViews.returnKeyType = UIReturnKeyDefault;
	textViews.keyboardType = UIKeyboardTypeDefault;	
	textViews.scrollEnabled = YES;
	textViews.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    [textViews setPlaceholder:tipText];
    [textViews setPlaceholderColor:[UIColor lightGrayColor]];
    [bgView addSubview:textViews];
    [self.view addSubview:bgView];

    //添加Email标题
    UITextView *emailTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, 230, 60, 50)];
    emailTextView.text=@"Email:";
    emailTextView.font=[UIFont fontWithName:@"Helvetica-Bold" size:14];
    emailTextView.editable = NO;
    [emailTextView setTextColor:[UIColor colorWithRed:255.0/255.0 green:111.0/255.0 blue:6.0/255.0 alpha:1.0f]];
    [self.view addSubview:emailTextView];
    
    UIImageView* emailBgView=[[UIImageView alloc] initWithFrame:CGRectMake(65,224,240,50)];
    NSString *filePath6=[[NSBundle mainBundle] pathForResource:@"email" ofType:@"png"];
    [emailBgView setImage:[UIImage imageWithContentsOfFile:filePath6]];  
    [emailBgView setUserInteractionEnabled:YES];
    
    //添加输入email的文本框
    contactTextViews = [[UIPlaceHolderTextView alloc] initWithFrame:CGRectMake(10, 8, 220, 30)];    
    //把换行键改成完成键
    contactTextViews.returnKeyType = UIReturnKeyDone;
    contactTextViews.textColor = [UIColor blackColor];
	contactTextViews.font = [UIFont fontWithName:@"Arial" size:14.0];
    contactTextViews.delegate = self;
	contactTextViews.backgroundColor = [UIColor whiteColor];
	contactTextViews.keyboardType = UIKeyboardTypeDefault;	
	contactTextViews.scrollEnabled = YES;
	contactTextViews.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    [contactTextViews setPlaceholder:@"请输入您的Email"];
    [contactTextViews setPlaceholderColor:[UIColor lightGrayColor]];
    [emailBgView addSubview:contactTextViews];
    [self.view addSubview:emailBgView];
    
    //添加发送按钮
    UIButton *goBtn = [UIButton buttonWithType:UIButtonTypeCustom]; 
    [goBtn setFrame:CGRectMake(95, 300, 130, 40)];
    NSString *filePath5=[[NSBundle mainBundle] pathForResource:@"buttonBg" ofType:@"png"];
    [goBtn setBackgroundImage:[UIImage imageWithContentsOfFile:filePath5] forState:UIControlStateNormal];
    [goBtn setBackgroundImage:[UIImage imageWithContentsOfFile:filePath5] forState:UIControlStateHighlighted];
    [goBtn setTitle:@"提 交" forState:UIControlStateNormal];
    [goBtn addTarget:self action:@selector(sendReport:) forControlEvents:UIControlEventTouchUpInside];
    goBtn.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:16];
    [self.view addSubview:goBtn];
    
}

//手势
-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer{
    //后退
    if(recognizer.direction==UISwipeGestureRecognizerDirectionRight) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

//完成键调用的方法
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{

    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
} 


- (void)backButtonPressd{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    //将当前视图推出栈，程序将进入上一视图
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)sendReport:(id)sender{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    [textViews resignFirstResponder];
    [contactTextViews resignFirstResponder];
    
    if(textViews.text.length == 0){
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"请输入内容。" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
    }
    else if(![self isValidEmail:contactTextViews.text]){
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"请输入正确的邮箱地址。" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
    }
    else {
        MoreManager *manager = [[MoreManager alloc] init];
        NSString *type = [recieveDictionary objectForKey:@"type"];
        BOOL isSuccess;
        if ([type isEqualToString:@"F"]) {
            isSuccess = [manager sendFeedBack:textViews.text contact:contactTextViews.text];
        }else{
            NSString *supId = (NSString *)[recieveDictionary objectForKey:@"supId"];
            isSuccess = [manager sendErrorReport:textViews.text supId:supId contact:contactTextViews.text]; 
        }
        if (isSuccess) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"感谢您的及时反馈，我们将会通过邮件的方式与您联系，点送的进步离不开您的支持，谢谢。" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            alertView.tag = 1;
            [alertView show];
            return;
        }
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {    
    if(alertView.tag == 1){
        [self backButtonPressd];
    }
}

//判断邮箱输入是否合法
- (BOOL)isValidEmail:(NSString *)checkString
{  
    NSString *Regex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];
    return [emailTest evaluateWithObject:checkString]; 
}

- (void)viewDidUnload
{
    self.textViews=nil;
    self.contactTextViews=nil;
    [super viewDidUnload];
}

//- (void)dealloc {
//
//}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(IBAction) slideFrameUp;
{
    [self slideFrame:YES];
}

-(IBAction) slideFrameDown;
{
    [self slideFrame:NO];
}

-(void) slideFrame:(BOOL) up
{
    const int movementDistance = 70; // 垂直偏移量
    const float movementDuration = 0.3f; // 动画时间
    
    int movement = (up ? -movementDistance : movementDistance);
    
    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    [UIView commitAnimations];
}

//textView开始编辑时，将页面向上偏移
- (void)textViewDidBeginEditing:(UITextView *)textView {
    [self slideFrameUp];
}

//textView开始编辑时，将页面向下偏移
- (void)textViewDidEndEditing:(UITextView *)textView{
    [self slideFrameDown];
}
@end
